package main

import (
	"bytes"
	"fmt"
	"runtime"
	"strconv"
	"sync"
)

type Local struct {
	cache *sync.Map
}

func NewLocal() *Local {
	return &Local{cache: &sync.Map{}}
}

func (l *Local) Add(key string, obj interface{}) {
	l.cache.Store(l.getLKey(key), obj)
}

func (l *Local) getLKey(key string) string {
	return fmt.Sprintf("%d_%s", l.getGoId(), key)
}

func (l *Local) Get(key string) interface{} {
	load, _ := l.cache.Load(l.getLKey(key))
	return load
}

func (l *Local) getGoId() uint64 {
	b := make([]byte, 64)
	runtime.Stack(b, false)
	b = bytes.TrimPrefix(b, []byte("goroutine "))
	b = b[:bytes.IndexByte(b, ' ')]
	n, _ := strconv.ParseUint(string(b), 10, 64)
	return n
}
